package com.example.ex;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.alibaba.fastjson.JSONObject;
import com.example.enums.CallBackEnum;
import com.example.vo.ResultVO;

/**
 * spring 3.2中，新增了@ControllerAdvice 注解，<br>
 * 可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute，<br>
 * 并应用到所有@RequestMapping中。
 * @author 765199214
 *
 */
@RestControllerAdvice 
//@ControllerAdvice //根据需要监测的controller上的注解区分使用
public class ExceptionAdvice extends AbstractBaseController {
	
	private Logger log = LoggerFactory.getLogger(ExceptionAdvice.class);
	
	/**
	 * 针对  MethodArgumentNotValidException 异常，做全局监听处理
	 * @param me
	 * @return
	 */
	//@ExceptionHandler(value = MethodArgumentNotValidException.class)
	public String MethodArgumentNotValidException1(MethodArgumentNotValidException me) {
		log.info("--->com.example.ex.ExceptionAdvice.MethodArgumentNotValidException1");
		BindingResult bindingResult = me.getBindingResult();
		List<ObjectError> allErrors = bindingResult.getAllErrors();
		ObjectError objectError = allErrors.get(0);
		return objectError.getDefaultMessage();
	}
	
	/**
	 * 针对  MethodArgumentNotValidException 异常，做全局监听处理
	 * @param me
	 * @return
	 */
	//@ExceptionHandler(value = MethodArgumentNotValidException.class)
	public JSONObject MethodArgumentNotValidException2(MethodArgumentNotValidException me) {
		log.info("--->com.example.ex.ExceptionAdvice.MethodArgumentNotValidException2");
		BindingResult bindingResult = me.getBindingResult();
		List<ObjectError> allErrors = bindingResult.getAllErrors();
		ObjectError objectError = allErrors.get(0);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code", 10000);
		jsonObject.put("msg", objectError.getDefaultMessage());
		jsonObject.put("data", "");
		return jsonObject;
	}
	
	/**
	 * 针对  MethodArgumentNotValidException 异常，做全局监听处理
	 * @param me
	 * @return
	 */
	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	public JSONObject MethodArgumentNotValidException(MethodArgumentNotValidException me) {
		log.info("--->com.example.ex.ExceptionAdvice.MethodArgumentNotValidException");
		BindingResult bindingResult = me.getBindingResult();
		List<ObjectError> allErrors = bindingResult.getAllErrors();
		ObjectError objectError = allErrors.get(0);
		String key = objectError.getDefaultMessage();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code", 10000);
		jsonObject.put("msg", super.getMessage(key, null));
		jsonObject.put("data", "");
		return jsonObject;
	}
}
